package com.fz.song.filter;

import com.fz.song.exception.VerificationCodeException;
import com.fz.song.handler.MyAuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class VerificationCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (!"/auth/form".equals(uri)) {
            chain.doFilter(request, response);
        } else {
            try {
                verificationCode(request);
            } catch (VerificationCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);
            }
            chain.doFilter(request, response);
        }
    }

    private void verificationCode(HttpServletRequest request) throws VerificationCodeException {
        String code = request.getParameter("captcha");
        HttpSession session = request.getSession();
        String saveCode = (String) session.getAttribute("captcha");
        if (!StringUtils.isEmpty(saveCode)) {
            session.removeAttribute("captcha");
        }
        if (!saveCode.equals(code) || StringUtils.isEmpty(code)) {
            throw new VerificationCodeException();
        }
    }
}
